<?php
/*
 * @Descripttion: 
 * @version: 1.0
 * @Author: Sam
 * @Date: 2022-05-06 15:01:17
 * @LastEditors: Sam
 * @LastEditTime: 2022-10-14 11:40:31
 */
namespace app\admin\controller;
use app\admin\model\StoreCategory as StoreCategoryModel;
use app\common\BaseController;

class StoreCategory extends BaseController {

    /**
     * 首页
     */
    public function index(){
        $page   = (int)request()->param('page', 0);
        $limit  = (int)request()->param('limit', 10);
        $search = request()->param();
        $where = [];
        if(isset($search['cate_name']) && $search['cate_name'] !=''){
             $where[] = ['cate_name','like',"%{$search['cate_name']}%"];
        }
        $query  = StoreCategoryModel::where($where);
        $total  = $query->count();
        $data   = $query->page($page, $limit)->order('sort desc,id desc')->select();
        return $this->success('', [
            'start' => $page,
            'limit' => $limit,
            'data'  => $data,
            'total' => $total,
        ]);
    }



    /**
     * 添加商品分类
     */
    public function create(){
        $data = request()->post();
        try {
            $this->validate($data, [
                'cate_name' => 'require',
            ], [
                'cate_name.require'  => '名称不得为空',
            ]);
        } catch (\Exception $e) {
            json_response(0,$e->getError());
        }
        $data['add_time']  = time();
        if(StoreCategoryModel::create($data)) json_response(1,'操作成功');
        json_response(0,'操作失败');
    }

    /**
     * 编辑分类
     */
    public function edit(){
        $data = request()->post();
        try {
            $this->validate($data, [
                'id' => 'require',
                'cate_name' => 'require',
            ], [
                'id.require'  => 'ID不得为空',
                'cate_name.require'  => '名称不得为空',
            ]);
        } catch (\Exception $e) {
            json_response(0,$e->getError());
        }
        if(StoreCategoryModel::update($data)) json_response(1,'操作成功');
            json_response(0,'操作失败');
    }

    /**
     * 详情
     * @param int $id
     * @return \think\response\Json
     * @author Sam
     * @date 2022-05-06
     */
    public function detail(int $id): \think\response\Json
    {
        try {
            $row  = StoreCategoryModel::where('id', $id)->find();
        } catch (DataNotFoundException | ModelNotFoundException | DbException $e) {
            return $this->error($e->getMessage());
        }

        return $this->success('', $row);
    }
    /**
     * 删除分类
     * @return [type] [description]
     */
    public function delete(){
        $ids = param_check('ids');
        $category = StoreCategoryModel::find($ids);
        if(StoreCategoryModel::where('pid',$ids)->count()) json_response(0,'该分类下有子分类，不能直接删除');
        if($category->delete()) json_response(1,'删除成功');
        json_response(0,'删除失败');
    }

}